package com.overkill.game;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.WindowManager;

public class TheGameActivity extends Activity implements GameOverListener {

	protected boolean menuPause = true;
	protected RenderView renderView;
	protected GameEngine gameEngine;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics metrics = new DisplayMetrics();
		((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
		GameEngine.SCALE = metrics.density;
		GameEngine.DEVICE_DENSITY = metrics.densityDpi;
	}

	public void inizialize(boolean menuPause, GameEngine gameEngine, int renderViewResId) {
		this.menuPause = menuPause;
		this.gameEngine = gameEngine;
		this.renderView = (RenderView) findViewById(renderViewResId);

		renderView.setEngine(gameEngine);
	}

	public void inizialize(GameEngine gameEngine, int renderViewResId) {
		this.gameEngine = gameEngine;
		this.renderView = (RenderView) findViewById(renderViewResId);

		renderView.setEngine(gameEngine);
	}

	@Override
	public void gameOver(GameOptions options) {

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Log.i("TheGameActivity", "onPrepareOptionsMenu");
		if (menuPause == false)
			super.onPrepareOptionsMenu(menu);

		if (gameEngine.gameRunning) {
			if (gameEngine.gamePaused)
				gameEngine.resumeGame();
			else
				gameEngine.pauseGame();
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus == false && renderView.initialized) {
			gameEngine.pauseGame();
		}
		if (hasFocus == true && renderView.initialized && gameEngine.gameRunning) {
			gameEngine.requestDraw();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (gameEngine.onKeyDown(keyCode, event)) {
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (gameEngine.onKeyUp(keyCode, event)) {
			return true;
		} else {
			return super.onKeyUp(keyCode, event);
		}
	}

	public boolean isMenuPause() {
		return menuPause;
	}

	public void setMenuPause(boolean menuPause) {
		this.menuPause = menuPause;
	}

	public RenderView getRenderView() {
		return renderView;
	}

	public void setRenderView(RenderView renderView) {
		this.renderView = renderView;
	}

	public GameEngine getGameEngine() {
		return gameEngine;
	}

	public void setGameEngine(GameEngine gameEngine) {
		this.gameEngine = gameEngine;
	}

}
